package com.pqtest.api.controller;
import com.alibaba.fastjson.JSONObject;
import javassist.NotFoundException;
import lombok.extern.java.Log;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.crossstore.ChangeSetPersister;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.AuthenticationException;

@Log
@RestControllerAdvice
public class ExceptionController {
    @ExceptionHandler(Exception.class)
    public Object jsonErrorHandler(/*HttpServletRequest req, */Exception e) {
        JSONObject p = new JSONObject();
        p.put("code","fail");
        p.put("data",null);
        p.put("msg",e.getMessage());
        log.warning(e.getMessage());
        return p;
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public Object handleDuplicateKeyException(DuplicateKeyException e) {
        JSONObject p = new JSONObject();
        p.put("code","fail");
        p.put("data",null);
        p.put("msg","记录已存在");
        log.warning(e.getMessage());
        return p;
    }

    @ExceptionHandler(OAuth2AccessDeniedException.class)
    public Object oauthErrorHandler(/*HttpServletRequest req, */OAuth2AccessDeniedException e) {
        JSONObject p = new JSONObject();
        p.put("code","fail");
        p.put("data",null);
        p.put("msg","鉴权失败");
        return p;
    }
    @ExceptionHandler(AuthenticationException.class)
    public Object authErrorHandler(AuthenticationException e) {
        JSONObject p = new JSONObject();
        p.put("code","fail");
        p.put("data",null);
        p.put("msg","无权限访问");
        return p;
    }
}
